package com.example.assignment1.server;

import com.example.assignment1.client.TypedStringService;
import com.example.assignment1.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.example.assignment1.server.PersistentThing;
import com.example.assignment1.server.PMF;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class TypedStringServiceImpl extends RemoteServiceServlet implements
		TypedStringService {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user != null) {
		  resp.setContentType("text/plain");
		  resp.getWriter().println("Hello, " + user.getNickname());
		} else {
		  resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
	}
	
	public String getUser()
	{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user != null) {
		  return user.getNickname();
		}
		return "";
	}
	
	public String getLogInLink(String returnUrl)
	{
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLoginURL(returnUrl);
	}
	
	public String getLogOutLink(String returnUrl)
	{
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLogoutURL(returnUrl);
	}

	private String test = "foo";
	PersistenceManager pm = PMF.get().getPersistenceManager();
	
	public String addString(String s)
	{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user != null) {
			PersistentThing p = new PersistentThing(s, user.getNickname());
			try{
				pm.makePersistent(p);
			}
			catch(Exception e)
			{
				return "ERROR PERSISTING";
			}
			return String.format("[%s] %s: %s<br />", p.getCreatedAt().toString(), p.getUsername(), p.getThing());
		}
		
		return "ERROR WITH LOGIN";
	}
	
	public String getAllStrings()
	{
		String text = "";
		String query = "select from "+PersistentThing.class.getName() + " order by created_at desc range 0, 20";
		List<PersistentThing> wordlist = (List<PersistentThing>)pm.newQuery(query).execute();
		if(wordlist.size() == 0)
			return "";
		
		for(int i = 0; i<wordlist.size(); i++)
		{
			PersistentThing temp = wordlist.get(i);
			text += String.format("[%s] %s: %s<br />", temp.getCreatedAt().toString(), temp.getUsername(), temp.getThing());
		}
		return text;
	}
	
	public String deleteAllStrings()
	{
		Query q = pm.newQuery(PersistentThing.class);
		
		Collection results = (Collection) q.execute();
		Iterator iter = results.iterator();
		while (iter.hasNext()) {
		    pm.deletePersistent(iter.next());
		}

		//String query = "delete from "+PersistentThing.class.getName();
		//pm.newQuery(query).execute();
		//if(wordlist.size() == 0)
		//return "";
		
		//pm.deletePersistentAll(wordlist);
		return "Cleared";
	}
}
